home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5708 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  53 lines

  1. Newsgroups: comp.lang.c
  2. Path: news.sprintlink.net!news1!news
  3. From: rclark@iquest.net (Robert B. Clark)
  4. Subject: Re: C beginner needs your help ASAP
  5. X-Nntp-Posting-Host: ind-004-236-169.iquest.net
  6. Message-ID: <3129dd8a.1042915@news.iquest.net>
  7. Sender: news@iquest.net (News Admin)
  8. Organization: IQuest Internet, Inc.
  9. X-Newsreader: Forte Agent .99d/16.182
  10. References: <4g862f$p0b@risky.ecs.umass.edu>
  11. Date: Tue, 20 Feb 1996 15:45:18 GMT
  12.  
  13. [Posted and emailed]
  14.  
  15. On Sun, 18 Feb 96 11:35:32 GMT, sebag@ecs.umass.edu wrote:
  16.  
  17. >I am a new C programmmer who desperately needs help.
  18. >I have been digging in the manuals for a way to do this but have still
  19. >come out empty handed. Here is the problem: I want to open files in a while
  20. >loop with different filenames. data0,data1,data2,data3, .. data1000 , ...
  21. >I need to increment an integer each time around then convert it to a string
  22. >and then somehow use strcat to combine the "data" with the integer string.
  23.  
  24. Are you trying to create unique temporary filenames?  If so, look up the
  25. tmpnam() function.  It will automatically increment filenames for you,
  26. making sure that the derived filename does not match any in the target
  27. directory.
  28.  
  29. Otherwise, here's a quick sketch that uses sprintf() to create a
  30. formatted string named 'filename':
  31.  
  32. #include <stdio.h>
  33. int main(void)
  34. {
  35.    int ctr;
  36.    char filename[13], basename[]="data";
  37.  
  38.    for (ctr=0; ctr<=1000; ctr++) /* Format & display 1001 filenames */
  39.    {
  40.       sprintf(filename,"%s%04d",basename,ctr);    
  41.       printf("\nThe derived filename is \"%s\"",filename);
  42.    }
  43.    return ctr>0;
  44. }
  45.  
  46. This will produce strings "data0000", "data0001", etc.  If you don't
  47. want the numeric suffix to be left-padded with zeroes, change the "%04d"
  48. specifier in the sprintf() statement to "%d".
  49. --
  50. Robert B. Clark <rclark@iquest.net>
  51. "Be wary of strong spirits.  It can make you shoot at tax collectors...
  52. and miss." --RAH
  53.